package com.szsh.aiot.hsm.controller;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.szsh.aiot.common.annotation.CustomPermission;
import com.szsh.aiot.common.annotation.Log;
import com.szsh.aiot.common.core.domain.AjaxResult;
import com.szsh.aiot.common.core.domain.RequestDto;
import com.szsh.aiot.common.enums.BusinessType;
import com.szsh.aiot.common.utils.StringUtils;
import com.szsh.aiot.hsm.service.WapLoginService;
import io.lettuce.core.api.reactive.RedisHashReactiveCommands;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.util.UriComponentsBuilder;

@Controller
@RequestMapping("/app/wap")
public class WapLoginController {
    private static final Logger LOGGER = LoggerFactory.getLogger(WapLoginController.class);

    private final WapLoginService wapLoginService;

    public WapLoginController(WapLoginService wapLoginService) {
        this.wapLoginService = wapLoginService;
    }

    /**
     * 2.1 天翼账号登录地址获取接口
     * @param requestDto 请求参数
     * @return 处理结果
     */
    @RequestMapping(value = "/login/url")
    @Log(title = "天翼账号登录地址获取接口", businessType = BusinessType.OTHER)
    @CustomPermission(isValidateTyAccount = false)
    @ResponseBody
    public AjaxResult getLoginUrl(@RequestBody RequestDto requestDto) {
        // 参数校验
        JsonObject requestParams = requestDto.getRequestJsonElement().getAsJsonObject();

        // returnUrl
        if (!requestParams.has("returnUrl")) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("[returnUrl缺失],requestParams:[" + requestParams + "]");
            }
            return AjaxResult.badRequest("returnUrl缺失");
        }
        JsonElement jsonElement = requestParams.get("returnUrl");
        if (!jsonElement.isJsonPrimitive()) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("[returnUrl格式错误],returnUrl:[" + jsonElement + "]");
            }
            return AjaxResult.badRequest("returnUrl格式错误");
        }
        String returnUrl = jsonElement.getAsString();
        if (StringUtils.isBlank(returnUrl)) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("[returnUrl为空],returnProject:[" + jsonElement + "]");
            }
            return AjaxResult.badRequest("returnUrl为空");
        }
        // 验证returnUrl是否正确
        try {
            UriComponentsBuilder.fromHttpUrl(returnUrl);
        } catch (Exception e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("returnUrl非法", e);
            }
            return AjaxResult.badRequest("returnUrl非法");
        }
        return wapLoginService.getLoginUrl(requestDto);
    }

    /**
     * 天翼账号登录返回
     * @param appId         天翼账号appId
     * @param paras         天翼账号加密数据
     * @param sign          天翼账号签名
     * @param returnUrl     跳转前端地址
     * @param customAppId   调用方appId
     * @param version       调用方密钥版本
     * @return 跳转页面
     */
    @RequestMapping(value = "/login/return")
    @Log(title = "天翼账号登录返回", businessType = BusinessType.OTHER)
    public String loginReturn(String appId, String paras, String sign, String returnUrl, String customAppId, String version) {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("天翼账号登录返回.appId:[{}],paras:[{}],sign:[{}],returnUrl:[{}],customAppId:[{}],version:[{}]",
                    appId, paras, sign, returnUrl, customAppId, version);
        }

        String errorMsg = null;
        String phoneNumber = null;
        if (StringUtils.isBlank(appId) || StringUtils.isBlank(paras) || StringUtils.isBlank(sign)
                || StringUtils.isBlank(returnUrl) || StringUtils.isBlank(customAppId) || StringUtils.isBlank(version)) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("天翼账号平台返回参数缺失,appid[{}],paras[{}],sign[{}],returnUrl:[{}],customAppId:[{}],version:[{}]",
                        appId, paras, sign, returnUrl, customAppId, version);
            }
            errorMsg = "天翼账号平台返回参数缺失";
        } else {
            phoneNumber = wapLoginService.getPhoneNumber(paras);
            if (StringUtils.isBlank(phoneNumber)) {
                if (LOGGER.isErrorEnabled()) {
                    LOGGER.error("获取手机号码失败");
                }
                errorMsg = "获取手机号码失败";
            }
        }

        AjaxResult ajaxResult;
        if (StringUtils.isBlank(phoneNumber) || StringUtils.isNotBlank(errorMsg)) {
            // 手机号码为空
            ajaxResult = AjaxResult.error(errorMsg);
        } else {
            // 有手机号码
            // 获取加密后的手机号码
            ajaxResult = wapLoginService.encryptPhoneNumber(phoneNumber, customAppId, version);
        }

        // 组装成最终地址
        UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromHttpUrl(returnUrl);
        // 添加参数
        ajaxResult.forEach(uriComponentsBuilder::queryParam);

        String url = uriComponentsBuilder.encode().build().toUriString();
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("跳转地址:[{}]", url);
        }

        return InternalResourceViewResolver.REDIRECT_URL_PREFIX + url;
    }

    /**
     * 天翼账号退出地址获取接口
     * @param requestDto 请求参数
     * @return 处理结果
     */
    @RequestMapping(value = "/logOut/url")
    @Log(title = "天翼账号退出地址获取接口", businessType = BusinessType.OTHER)
    @CustomPermission(isValidateTyAccount = false)
    @ResponseBody
    public AjaxResult getLogOutUrl(@RequestBody RequestDto requestDto) {
        // 参数校验
        JsonObject requestParams = requestDto.getRequestJsonElement().getAsJsonObject();

        // returnUrl
        if (!requestParams.has("returnUrl")) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("[returnUrl缺失],requestParams:[" + requestParams + "]");
            }
            return AjaxResult.badRequest("returnUrl缺失");
        }
        JsonElement jsonElement = requestParams.get("returnUrl");
        if (!jsonElement.isJsonPrimitive()) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("[returnUrl格式错误],returnUrl:[" + jsonElement + "]");
            }
            return AjaxResult.badRequest("returnUrl格式错误");
        }
        String returnUrl = jsonElement.getAsString();
        if (StringUtils.isBlank(returnUrl)) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("[returnUrl为空],returnProject:[" + jsonElement + "]");
            }
            return AjaxResult.badRequest("returnUrl为空");
        }
        // 验证returnProject是否正确
        try {
            UriComponentsBuilder.fromHttpUrl(returnUrl);
        } catch (Exception e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("returnUrl非法", e);
            }
            return AjaxResult.badRequest("returnUrl非法");
        }
        return wapLoginService.getLogOutUrl(requestDto);
    }

    /**
     * 天翼账号退出返回
     * @param appId         天翼账号appId
     * @param paras         天翼账号加密数据
     * @param sign          天翼账号签名
     * @param returnUrl     跳转前端地址
     */
    @RequestMapping(value = "/logOut/return")
    @Log(title = "天翼账号退出返回", businessType = BusinessType.OTHER)
    public String logOutReturn(String appId, String paras, String sign, String returnUrl) {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("天翼账号退出返回.appId:[{}],paras:[{}],sign:[{}],returnUrl:[{}]",
                    appId, paras, sign, returnUrl);
        }
        return InternalResourceViewResolver.REDIRECT_URL_PREFIX + returnUrl;
    }

}
